package pkg;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.naming.Context;
import java.util.HashMap;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class Controller
 */
@WebServlet("/Controller")
public class Controller extends HttpServlet
{
    private Map<String, IRequestHandler> m_map;
    
    private static final long serialVersionUID = 1L;

    public Controller()
    {
        m_map = new HashMap<String, IRequestHandler>();
        m_map.put("DUMP", new DumpHandler());
        m_map.put("TEST", new TestHandler());
        m_map.put("DATAFEED", new DataFeedHandler());
    }
    
    
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException
    {
        String page = request.getParameter("do");
        System.out.println("Controller page request: " + page);

        Context context= null;
        IStatelessBean stateless = null;
        IStatefulBean stateful = null;
        try
        {
            context = new InitialContext();
            stateless = (IStatelessBean) context.lookup("java:comp/env/StatelessBean");
            HttpSession session = request.getSession();
            session.setAttribute("statelessBean", stateless);
            
            if (session.getAttribute("statefulBean") == null)
            {
                session.setAttribute("statefulBean", (IStatefulBean) context.lookup("java:comp/env/StatefulBean"));    
            }
            stateful = (IStatefulBean)session.getAttribute("statefulBean"); 
        }
        catch (NamingException e)
        {
            throw new ServletException(e);
        }

        if (page == null)
        {
            page = "test";
        }

        IRequestHandler handler = null;
        handler = m_map.get(page.toUpperCase());
        if (handler == null)
        {
            throw new ServletException("Unknown request: " + page);
        }
        handler.handleRequest(request, response, stateless, stateful);
    }
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		doGet(request, response);
	}
	public void init(ServletConfig config) throws ServletException
	{
		// TODO Auto-generated method stub
	}
}
